package com.jzh.cmhSystem.controller;


import com.jzh.cmhSystem.biz.SectionService;
import com.jzh.cmhSystem.biz.UserAndDetailService;
import com.jzh.cmhSystem.biz.UserService;
import com.jzh.cmhSystem.biz.EnterpriseService;
import com.jzh.cmhSystem.entity.*;
import com.jzh.cmhSystem.utils.JwtUtil;
import com.jzh.cmhSystem.utils.MD5Utils;
import com.jzh.cmhSystem.utils.ThreadLocalUtil;
import io.swagger.annotations.Api;
import io.swagger.v3.oas.annotations.Operation;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.constraints.Pattern;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;


//@Tag(name = "登录", description = "这是描述")
@RestController
@RequestMapping("/api/auth")
@Api(tags = "登录相关", value = "这是描述")
//@Slf4j
//请求值校验
@Validated
public class LoginController {

    @Autowired
    private UserService userService;
    @Autowired
    private UserAndDetailService userAndDetailService;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private EnterpriseService enterpriseService;
    @Autowired
    private SectionService sectionService;

    @Operation(summary = "注册接口")
    @PostMapping("/register")

    public Result register(
//            @RequestParam String username,
            @Pattern(regexp = "^[a-zA-Z0-9]{4,10}$", message = "用户名应为4到10位英文字符或数字") String username,
            @Pattern(regexp = "^.{1,}$", message = "密码长度不合法") String password,
            @Pattern(regexp = "^[01]$", message = "角色不合法") String role,
            @RequestParam String captcha,
            @RequestParam String enterpriseNane,
            @RequestParam String enterpriseContact
    ) {
        Object code = redisTemplate.opsForValue().get("code");
        if (Objects.isNull(code) || !captcha.equalsIgnoreCase(code.toString())) {
            return Result.error("验证码错误");
        }
        if (Objects.equals(role, "1") && enterpriseNane.trim() == "") {
            return Result.error("公司名称不可为空");
        }
        if (Objects.equals(role, "1") && enterpriseContact.trim() == "") {
            return Result.error("公司联系方式不可为空");
        }
        User u = userService.findUserByName(username);
        if (u == null) {
            //没有占用
            //注册
            int userId = userService.register(username, password, Integer.parseInt(role));

            //注册公司
            Integer sectionId = null;
            Integer enterpriseId = null;
            if (Objects.equals(role, "1")) {

                Enterprise enterprise = new Enterprise();
                enterprise.setName(enterpriseNane);
                enterprise.setContact(enterpriseContact);
                enterprise.setAdminId(userId);
                enterpriseId = enterpriseService.addEnterprise(enterprise);
                System.out.println(enterpriseId);
                //添加部门
                Section section = new Section();
                section.setName("总经理");
                section.setEnterpriseId(enterpriseId);
                sectionId = sectionService.addSection(section);
                System.out.println(sectionId);
            }
            //添加个人信息
            UserAndDetail userAndDetail = new UserAndDetail();
            userAndDetail.setUserId(userId);
            userAndDetail.setEnterpriseId(enterpriseId);
            userAndDetail.setSectionId(sectionId);
            userAndDetailService.addDetail(userAndDetail);
            return Result.success();
        } else {
            //占用
            return Result.error("用户名已被占用");
        }
    }

    @Operation(summary = "用户登录")
    @PostMapping("/login")
    public Result login(
            @RequestParam String username,
            @RequestParam String password) {
        //查询用户
        User tuser = userService.findUserByName(username);
        if (tuser == null) {
            return Result.error("用户名不存在");
        }
        if (Objects.equals(MD5Utils.getMD5String(password), tuser.getPassword())) {
            HashMap<String, Object> claims = new HashMap<>();
            claims.put("id", tuser.getId());
            claims.put("username", tuser.getUsername());
            String token = JwtUtil.genToken(claims);
            //返回个人信息
            HashMap<String, Object> returnClaims = new HashMap<>();
            User returnUser = userService.findUserByName(tuser.getUsername());
            if (returnUser.getRole() > 1) {
                return Result.error("您没有登录权限");
            }
            returnClaims.put("token", token);
            returnClaims.put("info", returnUser);
            return Result.success(returnClaims);
        }
        return Result.error("密码错误");
    }

    @Operation(summary = "用户信息查询")
    @GetMapping("/user_info")
    public Result<User> userInfo() {
        //查询用户
        Map<String, Object> map = ThreadLocalUtil.get();
        String username = (String) map.get("username");
        User tuser = userService.findUserByName(username);
        return Result.success(tuser);
    }

    @Operation(summary = "修改密码")
    @PatchMapping("/updatePwd")
    public Result updatePwd(@RequestBody Map<String, String> params) {
        //校验参数
        String oldPwd = params.get("old_pwd");
        String newPwd = params.get("new_pwd");
        String rePwd = params.get("re_pwd");
        if (!StringUtils.hasLength(oldPwd) || !StringUtils.hasLength(newPwd) || !StringUtils.hasLength(rePwd)) {
            return Result.error("缺少必要参数");
        }
        //校验原密码
        Map<String, Object> map = ThreadLocalUtil.get();
        User tuser = userService.findUserByName((String) map.get("username"));
        if (!tuser.getPassword().equals(MD5Utils.getMD5String(oldPwd))) {
            return Result.error("原密码错误");
        }

        if (!newPwd.equals(rePwd)) {
            return Result.error("两次填写的新密码不一样");
        }
        //更新密码

        userService.updatePwd(rePwd);
        return Result.success();
    }
}
